<template>
	<div class="container" >
		<div class="form-box" style="width:100%" >
			<el-form :model="productAttributeForm" :label-width="formLabelWidth">
				<el-header>
					<el-button type="primary" size="medium" @click="onSubmit" plain>保存</el-button>
					<el-button type="success" size="medium" @click="onReset" plain>重置数据</el-button>
					<el-button @click="func_back" size="medium" plain>返回</el-button>
				</el-header>
				<el-container style="width:100%;">
					<el-main >
					<el-tabs type="border-card">
						<el-tab-pane label="商品属性">
							<el-divider content-position="left">商品属性配置</el-divider>
							<div :key="item" v-for="(item, index) in attrValueInput" >
								<el-form-item v-if="item.inputType === '11010001'" :label="item.attrName">
									<template #default="scope">
										<el-input v-model="item.attrId" v-if="false"/>
										<el-input class="handle-input" v-model="item.attrValue" />
										<el-input v-model="item.attrValId" v-if="false" />
									</template>
								</el-form-item>
								<el-form-item v-if="item.inputType === '11010002'" :label="item.attrName">
									<el-input v-model="item.attrValue" v-if="false"/>
									<el-input v-model="item.clasId" v-if="false"/>
									<el-input v-model="item.attrId" v-if="false"/>
									<el-input v-model="item.inputType" v-if="false"/>
									<el-select v-model="item.attrValId" placeholder="请选择">
										<el-option v-for="(item, index) in customOptionsChild" :key="index" :label="item.attrValLabel" :value="item.attrValId" />
                        			</el-select>
									<!-- <el-table :data="item.child" border class="table" header-cell-class-name="table-header" default-expand-all >
										<el-table-column prop="attrId" label="属性ID" >
											<template #default="scope">
												<el-input class="handle-input" v-model="scope.row.attrValId" />
											</template>
										</el-table-column>
										<el-table-column prop="attrValue" label="商品属性" >
											<template #default="scope">
											{{scope.row.strAttrVal}}
											</template>
										</el-table-column>
										<el-table-column label="属性值">
											<template #default="scope">
												<el-input class="handle-input" v-model="scope.row.attrVal" />
											</template>
										</el-table-column>
									</el-table> -->
								</el-form-item>
							</div>
						</el-tab-pane>
						<el-tab-pane label="商品规格">
							<!-- <el-input v-model="productAttributeForm.productSpecParam" /> -->
							<el-input class="handle-input mr10" v-model="inputSpecColumnName" />
							<el-button @click="func_add_CustomSpecColumn" plain>添加列</el-button>
							<el-button @click="func_add_CustomSpecData" plain>添加行</el-button>
							<el-button @click="func_clr_CustomSpecTable" plain>初始化表格</el-button>
							<el-button @click="func_cal_CustomSpecTable" plain>绑定商品规格</el-button>
							<el-divider content-position="left">自定义规格</el-divider>
							<el-table :data="customSpecTableData" border style="width:100%;" header-cell-class-name="table-header">
								<!-- 动态列 -->
								<el-table-column  v-for="(item, index) in dynamicTableColumns" :key="index" :label="item.label" :prop="item.prop" fit :min-width="item.width">
									<template #default="scope">
										<el-input fixed="right" style="width:140px" maxlength="10"  v-model="scope.row.inputSpecColumnVal0" v-if="index ===0"/>
										<el-input fixed="right" style="width:140px" maxlength="10"  v-model="scope.row.inputSpecColumnVal1" v-if="index ===1"/>
										<el-input fixed="right" style="width:140px" maxlength="10"  v-model="scope.row.inputSpecColumnVal2" v-if="index ===2"/>
									</template>
								</el-table-column>
								<el-table-column label="会员价格" prop="uPrice">
									<template #default="scope">
										<el-input style="width:140px" maxlength="10"  v-model="scope.row.uPrice" />
									</template>
								</el-table-column>
								<el-table-column label="价格" prop="price">
									<template #default="scope">
										<el-input style="width:140px" maxlength="10"  v-model="scope.row.price" />
									</template>
								</el-table-column>
								<el-table-column label="库存数量" prop="inventoryNumber">
									<template #default="scope">
										<el-input style="width:140px" maxlength="5"  v-model="scope.row.inventoryNumber" />
									</template>
								</el-table-column>
								<el-table-column label="锁定库存数量" prop="sockInventoryNumber">
									<template #default="scope">
										<el-input style="width:140px" maxlength="5"  v-model="scope.row.sockInventoryNumber" />
									</template>
								</el-table-column>
							</el-table>
						</el-tab-pane>
					</el-tabs>
					</el-main>
				</el-container>
			</el-form>
		</div>
	</div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { findAttributeListByClassifyId, findAttributesByProductAndClassifyId, } from "../../../../api/hairmanager/productAttribute.js";
import { findProductInfoListById, saveProductSpecInfo, saveProductAttrInfo } from "../../../../api/hairmanager/products";

export default {
    name: "productSpecForm",
  	props:{
        selectValue: Object,
	},
	emits: ["productSpecFormData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
		const SUCCMESS_BUNDATA_DIALOG_MESSAGE = "编辑数据成功";
		let id = route.query.id;
        const productSpecForm = reactive({
			id: 0,
			productId: 0,
			productClassifyId: 0,
			// 商品属性
			attributeList: [{
				id: 0,
				attrId: 0,
				attrLabel: '',
				attrValId: '',
				attrValue: '',
				sort: 0,
			}],
			// 商品规格
			specialList:[],
        });
		const attrValueInput = ref([]);
		const productAttributeList = ref([]);
		const productAttributeForm = reactive({
		});
		const classifyId = ref(0);
		// =========================================================================================
        const func_onLoad = () => {
            if (id > 0 ){
                findProductInfoListById(id).then((res) => {
                    if(res.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        // Object.keys(res.data).forEach((item) => {
                        //     productSpecForm[item] = res.data[item];
                        // });
						let a = res.data['productClassifyId'].split(",");
						let productClassifyId = a[a.length-1];
						productSpecForm['productClassifyId'] = productClassifyId; // res.data['productClassifyId'];
						productSpecForm['productId'] = res.data['id'];
						classifyId.value = productSpecForm['productClassifyId'];
						func_loadClassifyAttribute();
                    }
                });
            }
        };
		func_onLoad();
        // 主业务处理 ========================================================================================= START
		const customOptionsChild = ref([]);
		const func_loadClassifyAttribute = () => {
			let classifyIds = classifyId.value.split(",");
			let obj = {productId: id, classifyId:classifyIds[classifyIds.length-1]};
			attrValueInput.value = [];
			findAttributesByProductAndClassifyId(obj).then((res) => {
				res.data.forEach((element) => {
					var obj = { attrId: 0, attrName: '', attrValue: '', attrValId: 0, clasId: 0, inputType: '',};
					obj['attrId'] = element['id'];
					obj['attrValId'] = element['attributesValueOptionId'];
					obj['attrValue'] = element['strInputAttributeValue'];
					obj['attrName'] = element['attrName'];
					obj['inputType'] = element['inputType'];
					obj['clasId'] = classifyId.value;
					attrValueInput.value.push(obj);
					// 拼接制作自定义的数据下拉选项
					if(element['inputType'] === "11010002") {
						if(null != element['attributeLabels']) {
							element['attributeLabels'].forEach((subElement) => {
								var customOptObj = { attrId: 0, attrName: '', attrValLabel: '', attrVal: '', attrValId: 0, clasId: 0, inputType: '',};
								customOptObj['attrId'] = element['id'];
								customOptObj['attrValId'] = subElement['id'];
								customOptObj['attrValLabel'] = subElement['attrLabel'];
								customOptObj['attrVal'] = '';
								customOptObj['attrName'] = element['attrName'];
								customOptObj['inputType'] = element['inputType'];
								customOptObj['clasId'] = classifyId.value;
								customOptionsChild.value.push(customOptObj);
							});
						}
					}
				});
			});
		}
        // 提交
        const onSubmit = () => {
			productSpecForm['specialList'] = [];
			productSpecForm['attributeList'] = attrValueInput.value;
			saveProductAttrInfo(productSpecForm).then((res) => {
				if(res.code != 200) {
					if(res.type == 0) {
						ElMessage.warning(res.data.msg);
					} else {
						ElMessage.error(res.data.msg);
					}
				} else {
					func_loadClassifyAttribute();
					ElMessage.success(SUCCMESS_BUNDATA_DIALOG_MESSAGE);
				}
			});
        };
        // 重置
        const onReset = () => {
            
        };
        // 取消
        const func_back = () => {
            router.push({path: '/products', query:{id: 0}});
        };
		// 主业务处理 ========================================================================================= END
		// 规格图片处理 ========================================================================================= START
		// 规格图片处理 ========================================================================================= END
		// 自定义规格属性处理 ========================================================================================= START
		const customSpecTableData = ref([]);
		const inputSpecColumnName = ref('');
		const dynamicTableColumns = ref([]);
		let popColumnIndex = ref(0);
		let _sheep = [];
		const func_add_CustomSpecColumn = () => {
			if(inputSpecColumnName.value.length === 0) {
				ElMessage.warning('请填写自定义规格栏');
				return false;
			}
			if(popColumnIndex.value < 3) {
				var str_temp = 'inputSpecColumnVal'+''+popColumnIndex.value;
				dynamicTableColumns.value.push({prop: str_temp, label: inputSpecColumnName.value, type: '', width: '150' });
				popColumnIndex.value = popColumnIndex.value+1;
				_sheep.push(inputSpecColumnName.value);
			} else {
				ElMessage.warning('最高只能添加3个规格');
			}
		};
		const func_add_CustomSpecData = () => {
			switch (popColumnIndex.value) {
				case 0:
					ElMessage.warning('请添加一个商品规格');
					break;
				case 1:
					customSpecTableData.value.unshift({
						inputSpecColumnVal0: '',
						uPrice: 0,
						price: 0,
						inventoryNumber: 0,
						sockInventoryNumber: 0,
					});
					break;
				case 2:
					customSpecTableData.value.unshift({
						inputSpecColumnVal0: '',
						inputSpecColumnVal1: '',
						uPrice: 0,
						price: 0,
						inventoryNumber: 0,
						sockInventoryNumber: 0,
					});
					break;
				case 3:
					customSpecTableData.value.unshift({
						inputSpecColumnVal0: '',
						inputSpecColumnVal1: '',
						inputSpecColumnVal2: '',
						uPrice: 0,
						price: 0,
						inventoryNumber: 0,
						sockInventoryNumber: 0,
					});
					break;
				default:
					break;
			}
		};
		const func_clr_CustomSpecTable = () => {
			dynamicTableColumns.value = [];
			customSpecTableData.value = [];
			popColumnIndex.value = 0;
		};
		const func_cal_CustomSpecTable = () => {
			customSpecTableData.value.forEach((element) => {
				let _sheep2 = [];
				dynamicTableColumns.value.forEach((itemA, index) => {
					let aObjc = {'columnName':'', 'value': ''};
					if(index === 0){
						aObjc = {'columnName':_sheep[0], 'value': element['inputSpecColumnVal0']};
					}else if (index === 1){
						aObjc = {'columnName':_sheep[1], 'value': element['inputSpecColumnVal1']};
					}else {
						aObjc = {'columnName':_sheep[2], 'value': element['inputSpecColumnVal2']};
					}
					_sheep2.push(aObjc);
				});
				var obj2 = {
					specPic: '',
					productId: id,
					price: element['price'],
					uPrice: element['uPrice'],
					inventoryNumber: element['inventoryNumber'],
					sockInventoryNumber: element['sockInventoryNumber'],
					productSpecName: JSON.stringify(_sheep),
					productSpecInfo: JSON.stringify(_sheep2),
				};
				saveProductSpecInfo(obj2).then((res) => {
					if(res.code != 200) {
						if(res.type == 0) {
							ElMessage.warning(res.data.msg);
						} else {
							ElMessage.error(res.data.msg);
						}
					} else {
						func_loadClassifyAttribute();
						ElMessage.success(SUCCMESS_BUNDATA_DIALOG_MESSAGE);
					}
				});
			});
		};
		// 自定义规格属性处理 ========================================================================================= END
        // 业务数据监听
        watch(() => props.selectValue, (val) => {

        },{deep: true,immediate: true});
        return {
			// 系统变量
            formLabelWidth, productSpecForm, attrValueInput, productAttributeList, productAttributeForm,
			classifyId, customOptionsChild,
			// 主业务调用方法
            onSubmit, onReset, func_back, func_loadClassifyAttribute,
			// 自定义规格表数据
			inputSpecColumnName, dynamicTableColumns, customSpecTableData, popColumnIndex,
			func_add_CustomSpecColumn, func_add_CustomSpecData, func_clr_CustomSpecTable, func_cal_CustomSpecTable,
        };
    },
};
</script>
<style scoped>
.handle-box {
    margin-bottom: 20px;
}
.handle-select {
    width: 120px;
}
.handle-input {
    width: 200px;
    display: inline-block;
}
.table {
    width: 70%;
    font-size: 14px;
}
.box-card {
	width:300px;
}
.mr10 {
    margin-right: 10px;
}
</style>